<template>
  <el-form
    :model="user"
    status-icon
    ref="userForm"
    label-width="100px"
    class="userForm"
    :rules="formRules"
    style="width: 400px; margin: 0 auto"
  >
    <!-- 新增注册选项卡切换 -->
    <div class="form-header">
      <h2>{{ registerStatus ? "用户注册" : "用户登录" }}</h2>
      <el-link type="primary" @click="toggleRegisterStatus">
        {{ registerStatus ? "已有账号？立即登录" : "没有账号？立即注册" }}
      </el-link>
    </div>

    <!-- 账号/邮箱字段 -->
    <el-form-item label="邮箱" prop="account">
      <el-input
        v-model="user.account"
        :placeholder="registerStatus ? '请输入注册邮箱' : '请输入登录邮箱'"
      ></el-input>
    </el-form-item>

    <!-- 密码字段 -->
    <el-form-item label="密码" prop="password">
      <el-input
        placeholder="请输入密码"
        type="password"
        v-model="user.password"
        show-password
      ></el-input>
    </el-form-item>

    <!-- 新增确认密码字段 -->
    <el-form-item v-if="registerStatus" label="确认密码" prop="confirmPassword">
      <el-input
        placeholder="请再次输入密码"
        type="password"
        v-model="user.confirmPassword"
        show-password
      ></el-input>
    </el-form-item>

    <!-- 验证码字段 -->
    <el-form-item label="验证码" prop="code">
      <el-input
        v-model="user.code"
        placeholder="请输入验证码"
        autocomplete="off"
      ></el-input>
      <img :src="captchaUrl" alt="验证码" @click="refreshCode" />
    </el-form-item>

    <!-- 提交按钮 -->
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">
        {{ registerStatus ? "立即注册" : "立即登录" }}
      </el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "axios";
import VueCookies from "vue-cookies";
// ...原有导入保持不变...
const captchaUrl = ref("");
// 新增响应式状态
const registerStatus = ref(false);
const OK = 200;
const router = useRouter();
const userForm = ref(null);
const user = ref({
  account: "",
  password: "",
  code: "",
});
const formRules = reactive({
  account: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    {
      type: "email",
      message: "请输入正确的邮箱格式",
      trigger: ["blur", "change"],
    },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 6, max: 16, message: "密码长度在6-16位之间", trigger: "blur" },
  ],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (registerStatus.value && value !== user.value.password) {
          callback(new Error("两次输入密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  code: [
    { required: true, message: "验证码不能为空", trigger: "blur" },
    { len: 4, message: "验证码长度为4位", trigger: "blur" },
  ],
});
const refreshCode = () => {
  captchaUrl.value = "/api/users/getKaptcha?time=" + new Date().getTime();
};

// 新增注册状态切换
const toggleRegisterStatus = () => {
  registerStatus.value = !registerStatus.value;
  resetForm();
};

// 重构提交方法
const handleSubmit = () => {
  userForm.value.validate(async (valid) => {
    if (!valid) return;

    try {
      const apiPath = registerStatus.value
        ? "/api/users/register"
        : "/api/users/login";
      const res = await axios.post(apiPath, user.value);

      if (res.data.code === OK) {
        ElMessage.success(registerStatus.value ? "注册成功" : "登录成功");
        if (registerStatus.value) {
          toggleRegisterStatus(); // 注册成功后自动切换回登录
        } else {
          VueCookies.set("token", res.data.data, 60 * 30);
          router.push({ name: "Home" });
        }
      } else {
        ElMessage.error(res.data.message);
        refreshCode();
      }
    } catch (error) {
      ElMessage.error(error.response?.data?.message || "请求失败");
      refreshCode();
    }
  });
};

// 修改测试方法
const test = () => {
  user.value = registerStatus.value
    ? { account: "new@163.com", password: "123456", code: "" }
    : { account: "test@163.com", password: "123456", code: "" };
};
onMounted(() => {
  // tryToAdminPage()
  test();
  refreshCode();
});
</script>

<style scoped>
/* 新增头部样式 */
.form-header {
  margin-bottom: 30px;
  text-align: center;
}
.form-header h2 {
  margin-bottom: 10px;
  color: #409eff;
}
</style>
